package com.dc.datacollect.helpers;

import com.dc.datacollect.constant.BaseConstant;
import com.dc.datacollect.dto.SysUserDTO;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * session提供器
 *
 * @author zhuangjie
 * @date 2023/06/19
 */
public class SessionProvide {
    private static HttpSession getSession() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        // 判断当前线程是否正在处理 Web 请求
        if (attributes == null) {
            System.err.println("当前线程非 Web 请求线程，无法获取 HttpServletRequest");
            return null;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = requestAttributes.getRequest();
        // 获取 HttpSession 对象
        return request.getSession(true);
    }
    /**
     * 获取 Session 中指定 key 对应的值
     *
     * @param key   存储在 Session 中的 key 值
     * @param clazz 返回值类型
     * @return 返回指定类型的值，如果不存在则返回 null
     */
    public static<T> T  get(String key,Class<T> clazz) {
        HttpSession session = getSession();
        if (session == null ) {
            return null;
        }
        // 获取 key 对应的值
        Object value = session.getAttribute(key);
        if (value == null || !clazz.isAssignableFrom(value.getClass())) {
            return null;
        }
        return clazz.cast(value);
    }
    public static SysUserDTO getLoginObject() {
        return get(BaseConstant.USER_SESSION_KEY, SysUserDTO.class);
    }
    /**
     * 将指定的 key-value 数据存储到 Session 中
     *
     * @param key   要存储的 key 值
     * @param value 要存储的值
     */
    public static boolean set(String key, Object value) {
        HttpSession session = getSession();
        if (session == null ) {
            return false;
        }
        // 将 key-value 存入 Session
        session.setAttribute(key, value);
        return true;
    }

    /**
     * 删除在session的指定key
     *
     * @param key 关键
     */
    public static void remove(String key) {
        HttpSession session = getSession();
        if (session == null ) {
            return;
        }
        session.removeAttribute(key);
    }
}
